<template>
  <div class="pageRoll">
    <el-form :model="formModel" :rules="formRules" ref="formRef" label-width="100px">
      <div class="navLine">规格设置</div>
      <Goods-norms :classArr="formModel.productSpecs" @changeClass="changeClassHandle"></Goods-norms>
      <Goods-norms-detail ref="goodNormDetailRef" v-if="formModel.productSpecs && formModel.productSpecs.length > 0"
        :list="formModel.skuStocks" :classArr="formModel.productSpecs" :memoSpecList="memoSpecList"
        @changeNormList="changeNormList">
      </Goods-norms-detail>
      <div v-else>
        <el-form-item label="指导价" prop="originalPrice" style="margin-top: 10px">
          <el-input-number :min="0" :controls="false" v-model="formModel.originalPrice" placeholder="0"
            style="width: 500px" class="input_number"></el-input-number>
        </el-form-item>
        <el-form-item label="实售价" prop="price">
          <el-input-number :min="0" :controls="false" v-model="formModel.price" placeholder="0" style="width: 500px"
            class="input_number"></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number :step="1" v-model="formModel.stock" placeholder="0" style="width: 500px" :min="0"
            step-strictly :controls="false" :precision="0" class="input_number"></el-input-number>
        </el-form-item>
        <el-form-item label="商品限购">
          <el-input-number :step="1" v-model="formModel.perLimit" placeholder="0" style="width: 500px" :min="0"
            step-strictly :controls="false" :precision="0" class="input_number"></el-input-number>
        </el-form-item>
        <el-form-item label="商品重量" v-if="isWeight" prop="weight">
          <el-input-number :min="0" :controls="false" v-model="formModel.weight" placeholder="0" style="width: 500px">
          </el-input-number>
        </el-form-item>
      </div>
      <el-form-item label="商品积分">
        <el-input-number :step="1" v-model="formModel.giftPoint" placeholder="0" style="width: 500px" :min="0"
          step-strictly :controls="false" :precision="0" class="input_number"></el-input-number>
      </el-form-item>
      <!-- <div v-if="formModel.limitType !== 0">
        <div class="specitem">
          <el-radio v-model="formModel.limitType" :label="1" @change="radioMore = true">统一限购</el-radio>
          <div v-if="formModel.limitType !== 2" style="margin-left: 20px">
            <div class="specitem__inp">
              限购
              <el-input-number :min="0" :step="1" step-strictly :controls="false" class="specitem__inp--inside"
                v-model="unifyLimitNum" style=" ;"></el-input-number>件
            </div>
            <div class="valueName" style="width: 700px">
              <div class="flex" style="justify-content: space-between">
                <div style="width: 110px">规格值</div>
                <div style="width: 60px">指导价</div>
                <div style="width: 60px">实售价</div>
                <div style="width: 90px">库存</div>
                <div style="width: 60px" v-if="isWeight">重量</div>
                <div style="width: 40px">sku图</div>
                <div style="width: 30px">操作</div>
              </div>
              <div class="valueName__noList" v-if="!showAttributes">
                暂无数据~
              </div>
              <div class="valueName__List middle" v-for="(item, index) in formModel.skuStocks" :key="index" v-else>
                <el-input v-model="item.specs" style="width: 120px" maxlength="20"></el-input>
                <el-input-number :min="0" :controls="false" v-model="item.originalPrice" style="width: 70px">
                </el-input-number>
                <el-input-number :min="0" :controls="false" v-model="item.price" style="width: 70px"></el-input-number>
                <el-input-number :min="0" step-strictly :step="1" :controls="false" v-model="item.stock"
                  style="width: 100px"></el-input-number>
                <el-input-number :min="0" :controls="false" v-model="item.weight" style="width: 70px" v-if="isWeight">
                </el-input-number>
                <el-upload class="productImg__uploader product__productImg" :auto-upload="false"
                  :on-change="uploadSkuImg" action :show-file-list="false" style="width: 50px; height: 50px">
                  <i style="width: 50px; height: 50px; line-height: 50px"
                    class="el-icon-plus product__productImg--uploader--icon" @click="productSkuIndex = index"
                    v-if="item.pic === ''"></i>
                  <img :src="item.pic" alt="" style="width: 50px; height: 50px" @click="productSkuIndex = index"
                    v-else />
                </el-upload>
                <div @click="formModel.skuStocks.splice(index, 1)">删除</div>
              </div>
              <el-button type="primary" plain style="margin-top: 10px" size="small" @click="addSku">+ 添加规格</el-button>
            </div>
          </div>
        </div>
        <div class="specitem">
          <el-radio v-model="formModel.limitType" :label="2" class="specitem__inp" @change="radioMore = false">规格限购
          </el-radio>
          <div v-if="formModel.limitType === 2" style="margin-left: 20px">
            <div class="valueName" style="width: 700px">
              <div class="flex" style="justify-content: space-between">
                <div style="width: 150px">规格值</div>
                <div style="width: 100px">指导价</div>
                <div style="width: 100px">实售价</div>
                <div style="width: 100px">库存</div>
                <div style="width: 100px">限购</div>
                <div style="width: 100px" v-if="isWeight">重量</div>
                <div style="width: 70px">sku图</div>
                <div style="width: 40px">操作</div>
              </div>
              <div class="valueName__noList" v-if="!showAttributes">
                暂无数据~
              </div>
              <div class="valueName__List middle" v-for="(item, index) in formModel.skuStocks" :key="index" v-else>
                <el-input v-model="item.specs" style="width: 110px" maxlength="20"></el-input>
                <el-input-number :min="0" :controls="false" v-model="item.originalPrice" style="width: 70px">
                </el-input-number>
                <el-input-number :min="0" :controls="false" v-model="item.price" style="width: 70px"></el-input-number>
                <el-input-number :step="1" :min="0" step-strictly :controls="false" v-model="item.stock"
                  style="width: 70px"></el-input-number>
                <el-input-number :step="1" :min="0" step-strictly :controls="false" v-model="item.perLimit"
                  style="width: 70px"></el-input-number>
                <el-input-number :min="0" :controls="false" v-model="item.weight" style="width: 70px" v-if="isWeight">
                </el-input-number>
                <el-upload class="productImg__uploader product__productImg" :auto-upload="false"
                  :on-change="uploadSkuImg" action :show-file-list="false" style="width: 50px; height: 50px">
                  <i style="width: 50px; height: 50px; line-height: 50px"
                    class="el-icon-plus product__productImg--uploader--icon" @click="productSkuIndex = index"
                    v-if="item.pic === ''"></i>
                  <img :src="item.pic" alt v-else @click="productSkuIndex = index" style="width: 50px; height: 50px" />
                </el-upload>
                <div @click="formModel.skuStocks.splice(index, 1)">删除</div>
              </div>
              <el-button type="primary" plain style="margin-bottom: 20px" size="small" @click="addSku">+ 添加属性
              </el-button>
            </div>
          </div>
        </div>
        <div class="codeOne">
          商品积分：
          <el-input-number :step="1" :min="0" step-strictly :controls="false" v-model="formModel.giftPoint"
            style="width: 700px" placeholder="0" class="input_number"></el-input-number>
        </div>
      </div> -->

      <div class="navLine">分佣设置</div>

      <el-form-item label="分佣类型" style="margin-top: 25px">
        <el-radio :label="1" v-model="formModel.useDistribution">固定金额</el-radio>
        <el-radio :label="2" v-model="formModel.useDistribution">百分比</el-radio>
      </el-form-item>

      <el-form-item label="佣金规则" style="margin-top: 25px">
        <el-input-number :step="1" v-model="formModel.distributionAmount" placeholder="0" style="width: 500px" :min="0"
          step-strictly :controls="false" class="input_number"></el-input-number>
        {{ formModel.useDistribution === 1 ? "元" : "%" }}
      </el-form-item>

      <!-- <div >
      <div style="margin-left: 30px;">
      <span >分佣类型</span>
      <el-radio-group v-model="useDistribution" style=" margin-left: 12px;">
        <el-radio label="1">固定金额</el-radio>
        <el-radio label="2">百分比</el-radio>
      </el-radio-group>
    </div>
    <div class="commission">
       <div style="margin-right: 12px;margin-left: 30px;">佣金规则</div>
      <div>
      <div style="margin-top: 10px;">
        <span>佣金</span> 
        <el-input-number
          :min="0"
          :controls="false"
          v-model="distributionAmount"
          style="width: 125px; margin: 0px 13px"
          
        >
        </el-input-number>
          <span >{{ useDistribution === "1" ? "元" : "%" }}</span>
      </div>
      </div>
    </div>
  </div> -->

      <div class="navLine">其他信息</div>
      <el-form-item label="初始销量">
        <el-input-number :step="1" v-model="formModel.sale" placeholder="0" style="width: 500px" :min="0" step-strictly
          :controls="false" class="input_number"></el-input-number>
      </el-form-item>
      <el-form-item label="服务保障">
        <div v-for="item in serviceAssuranceList" :key="item.name">
          <el-checkbox v-model="item.state">
            <div class="serveMsg">
              <span style="width: 120px">{{ item.name }}</span>
              <span style="color: #c6c6c6">{{ item.text }}</span>
            </div>
          </el-checkbox>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref, Prop, Watch } from "vue-property-decorator";
import { upLoad } from "@/api/index";
import storage from "@/libs/storage";
import GoodsNorms from "@/views/goods/marketModel/components/GoodsNorms/GoodsNorms.vue";
import GoodsNormsDetail from "@/views/goods/marketModel/components/GoodsNorms/GoodsNormsDetail.vue";
import CommoditySpec from "@/views/goods/marketModel/components/GoodsNorms/CommoditySpec.vue";
import { ClassListType, NormType } from "../../../../GoodsNorms/goodNormType";
const checkPriceField = (message: string) => {
  return (rule, value, callback) => {
    if (!value) {
      return callback(new Error(message));
    }
    const priceReg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;

    if (!priceReg.test(value)) {
      return callback(new Error("请输入正确的价格"));
    }
    callback();
  };
};

const checkNumberField = (message?: string) => {
  return (rule, value, callback) => {
    if (!value) {
      return message ? callback(new Error(message)) : callback();
    }

    if (!Number.isSafeInteger(value)) {
      return callback(new Error("请输入正确的数字"));
    }
    callback();
  };
};

/**
 * 会员折扣
 */
interface MemberPriceDto {
  id: string;
  memberLevelId: string;
  memberLevelName: string;
  memberPrice: string;
  productId: string;
  skuId: string;
}

/**
 * 规格列表
 */
// interface Norms {
//   //   /** 规格值 */
//   //   specs: string;
//   //   /** 指导价 */
//   //   originalPrice: number;
//   //   /** 实售价 */
//   //   price: number;
//   //   /** 商品库存 */
//   //   stock: string;
//   //   /** 商品限购 */
//   //   perLimit: string;
//   //   /** sku图 */
//   //   pic: string;
//   //   /** 初始销量 */
//   //   sale: string;
//   //   /** 商品重量 */
//   //   weight: string;
//   //   id: string;
//   //   lowStock: string;
//   //   memberPrices: memberPrices[];
//   //   productId: string;
//   //   skuCode: string;
// }

/**
 * 编辑销售信息
 */
@Component({
  components: {
    GoodsNorms,
    GoodsNormsDetail,
    CommoditySpec,
  },
})
export default class NewGoodSellInfo extends Vue {
  @Prop({
    type: Object,
    default() {
      return null;
    },
  })
  readonly goodDetail: any;

  @Prop({
    type: String,
    default() {
      return "";
    },
  })
  logisticsId: any;

  @Watch("logisticsId")
  watchLogisticsId() {
    this.getLogMsg();
  }

  @Watch("formModel.skuStocks")
  getShowAttributes() {
    this.showAttributes = this.formModel.skuStocks.length > 0 ? true : false;
  }
  @Ref()
  readonly goodNormDetailRef: GoodsNormsDetail;
  radioMore = true;

  showAttributes = false;

  formModel = {} as any;

  limitNum = "";

  productSpecs: [];

  limitType: 0;
  /** 商品模板 */
  isWeight = false;

  formRules = {
    originalPrice: [
      {
        required: true,
        message: "请输入商品指导价",
        trigger: "blur",
        validator: checkPriceField("请输入商品指导价"),
      },
    ],
    price: [
      {
        required: true,
        message: "请输入商品实售价",
        trigger: "blur",
        validator: checkPriceField("请输入商品实售价"),
      },
    ],
    stock: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
    checkNumberField: [{ trigger: "blur", validator: checkNumberField() }],
    weight: [{ required: true, message: "请输入商品重量", trigger: "blur" }],
    dominoState: [
      { required: true, message: "请选择是否开启接龙", trigger: "blur" },
    ],
  };

  /** 上传sku下标 */
  productSkuIndex = 0;

  /** 统一限购数量 */
  unifyLimitNum = "0";

  /** 选择规格列表 */
  //   normsList: Norms[] = [];
  normsList = [];

  /** 服务保障 */
  serviceAssuranceList = [
    {
      name: "全场包邮",
      state: false,
      text: "所有商品均无条件包邮",
    },
    {
      name: "7天退换",
      state: false,
      text: "商家承诺7天无理由退换货",
    },
    {
      name: "48小时发货",
      state: false,
      text: "商家承诺订单在48小时内发布",
    },
    {
      name: "假一赔十",
      state: false,
      text: "若收到商品是假冒品牌，可获得十倍赔偿",
    },
    {
      name: "正品保证",
      state: false,
      text: "商家承诺商品正品质量",
    },
  ];
  // 存储规格明细列表
  memoSpecList = [];
  @Ref()
  readonly formRef: HTMLFormElement;

  mounted() {
    if (storage.get("allFoorm")) {
      this.formModel = JSON.parse(JSON.stringify(storage.get("allFoorm")));
      // storage.delete("formModel");
    } else {
      this.getModel();
    }
    this.setFormModel();
    this.getLogMsg();
  }

  getModel() {
    if (!this.goodDetail) {
      this.formModel = JSON.parse(JSON.stringify(this.$parent.goodFormModel));
      this.formModel.skuStocks = [
        {
          specs: "",
          originalPrice: 0,
          price: 0,
          stock: 0,
          perLimit: 0,
          pic: "",
          sale: "0",
          weight: "0",
          id: "",
          lowStock: "",
          memberPrices: [],
          skuRebates: [],
          productId: "",
          skuCode: "",
          productSpecNames: [],
        },
      ];
    }
  }

  /**
   * 获取物流模板
   */
  getLogMsg() {
    this.isWeight = this.$parent.isWeight;
  }

  /**
   * 还原表单数据
   */
  setFormModel() {
    let goodDetail = this.goodDetail;
    if (storage.get("allFoorm") !== null) {
      if (Object.keys(storage.get("allFoorm")).length !== 0) {
        goodDetail = storage.get("allFoorm");
      }
    }
    if (goodDetail) {
      const formModel = goodDetail;
      for (const key of Object.keys(formModel)) {
        const value = goodDetail[key];
        if (value) {
          formModel[key] = value;
        }
      }
      formModel.weight = goodDetail.weight;
      formModel.skuStocks = goodDetail.skuStocks;
      this.setServiceAssuranceList(goodDetail.serviceIds);
      if (
        goodDetail.productSpecs.length === 0 &&
        goodDetail.skuStocks.length > 0
      ) {
        const skuStockItem = formModel.skuStocks[0];
        formModel.originalPrice = skuStockItem.originalPrice;
        formModel.price = skuStockItem.price;
        formModel.stock = skuStockItem.stock;
        formModel.perLimit = skuStockItem.perLimit;
        formModel.weight = skuStockItem.weight;
      }
      this.memoSpecList = formModel.skuStocks;
      this.formModel = JSON.parse(JSON.stringify(formModel));
      // console.log("还原表单数据", goodDetail, { ...formModel });
    } else {
      this.formModel = JSON.parse(JSON.stringify(this.$parent.goodFormModel));
    }
  }
  getNewForm() {
    if (this.formModel.productSpecs.length === 0) {
      const temStock = this.formModel.skuStocks;
      this.formModel.skuStocks = [];
      this.formModel.skuStocks.push({
        originalPrice: this.formModel.originalPrice,
        price: this.formModel.price,
        stock: this.formModel.stock,
        weight: this.formModel.weight,
        perLimit: this.formModel.perLimit,
        id: temStock[0] && temStock[0].id ? temStock[0].id : "",
        lowStock: 0,
        memberPrices: temStock[0] ? temStock[0].memberPrices : [],
        skuRebates: temStock[0] ? temStock[0].skuRebates : [],
        memberType: temStock[0] ? temStock[0].memberType : null,
        rebateType: temStock[0] ? temStock[0].rebateType : null,
        productId: temStock.productId,
      });
    }
    this.formModel.serviceIds = this.getServiceIds();
    return JSON.parse(JSON.stringify(this.formModel));
  }

  async getFormModel() {
    try {
      await this.validate();
      await this.getSkuStocks();
      const formModel = this.formModel;
      console.log("formModel",formModel)
      //   const skuStocks = this.getSkuStocks();
      return {
        unit: "克", // 商品重量
        weight: "0", // 商品长度
        useDistribution: formModel.useDistribution,
        distributionAmount: formModel.distributionAmount,
        // launchArea: formModel.launchArea,
        // addLaunchArea: formModel.addLaunchArea,
        skuStocks: formModel.skuStocks,
        giftPoint: formModel.giftPoint,
        sale: formModel.sale,
        serviceIds: this.getServiceIds(),
        dominoState: formModel.dominoState,
        limitType: formModel.limitType,
        productSpecs: formModel.productSpecs,
        version: formModel.skuStocks[0].version,
      };
    } catch (error) {
      console.log(error);
      return Promise.reject(false);
    }
  }

  /**
   * 获取商品sku
   */
  getSkuStocks() {
    const formModel = this.formModel as any;
    const isMultiSpec = formModel.productSpecs.length;
    const limitType = formModel.limitType;
    if (!isMultiSpec) {
      const skuItem = {
        specs: "",
        originalPrice: formModel.originalPrice,
        price: formModel.price,
        stock: formModel.stock,
        perLimit: formModel.perLimit,
        pic: formModel.pic,
        // sale: formModel.sale,
        id:
          formModel.skuStocks[0] && formModel.skuStocks[0].id
            ? formModel.skuStocks[0].id
            : "",
        lowStock: formModel.lowStock,
        memberPrices: formModel.skuStocks[0]
          ? formModel.skuStocks[0].memberPrices
          : [],
        skuRebates: formModel.skuStocks[0]
          ? formModel.skuStocks[0].skuRebates
          : [],
        memberType: formModel.skuStocks[0]
          ? formModel.skuStocks[0].memberType
          : null,
        rebateType: formModel.skuStocks[0]
          ? formModel.skuStocks[0].rebateType
          : null,
        productId: formModel.productId,
        skuCode: "",
        weight: formModel.weight,
        version:formModel.skuStocks.length>0?formModel.skuStocks[0].version:'',
      };
      this.formModel.skuStocks = [skuItem];
    } else {
      this.formModel.skuStocks = this.goodNormDetailRef.getNormList();
    }

    if (!limitType) {
      //   const normsList = this.normsList;
      const isUnifyLimit = this.formModel.limitType === 1; // 是否为统一限购
      const unifyLimitNum = this.unifyLimitNum;
      this.formModel.skuStocks = this.formModel.skuStocks.map((item) => {
        return {
          ...item,
          perLimit: isUnifyLimit ? unifyLimitNum : item.perLimit,
        };
      });
      //   return skuStocks;
    }
  }

  /**
   * 对整个表单进行校验
   */
  validate() {
    return this.formModel.productSpecs.length === 0 && this.formRef.validate();
  }

  // validateNormsList() {
  //   // const isUnifyLimit = this.formModel.limitType === 1; // 是否为统一限购
  //   // const unifyLimitNum = this.unifyLimitNum;
  //   // if (isUnifyLimit && !unifyLimitNum) {
  //   //   return Promise.reject(false);
  //   // }

  //   const skuStocks = this.formModel.skuStocks;
  //   let flag = skuStocks.every((item) => {
  //     const { specs, originalPrice, price, stock } = item;
  //     return specs && originalPrice && price && stock;
  //   });

  //   if (flag && skuStocks.length > 0) {
  //     return true;
  //   } else {
  //     return Promise.reject(false);
  //   }
  // }

  // /**
  //  * 移除表单项的校验结果
  //  */
  // clearValidate() {
  //   this.formRef.clearValidate();
  // }

  /**
   * 获取服务保障
   */
  getServiceIds(): string {
    return this.serviceAssuranceList
      .filter((item) => item.state)
      .map((item) => item.name)
      .join(",");
  }

  /**
   * 还原服务保障
   */
  setServiceAssuranceList(serviceIds = "") {
    if (serviceIds) {
      const serviceIdArr = serviceIds.split(",");
      const isInclueDelivery = serviceIdArr.find((item) => {
        return item.indexOf("发货") !== -1;
      });
      this.serviceAssuranceList.forEach((item) => {
        if (item.name.indexOf("发货") !== -1 && isInclueDelivery) {
          const deliveryNumber = Number(
            isInclueDelivery.match(/[0-9]/gi).join(""),
          );
          this.deliveryTime = deliveryNumber;
          item.name = `${deliveryNumber}天发货`;
          item.state = true;
        } else {
          item.state = serviceIds.indexOf(item.name) !== -1;
        }
      });
    }
  }

  /**
   * 添加规格
   */
  addSku(productSpecNames) {
    let tempArr = [];
    if (Array.isArray(productSpecNames)) {
      tempArr = productSpecNames.map((item) => {
        return item.name;
      });
    } else {
      tempArr.push(productSpecNames.name);
    }
    return {
      specs: "",
      originalPrice: 0,
      price: 0,
      stock: "0",
      perLimit: "0",
      pic: "",
      sale: "0",
      weight: "0",
      id: "",
      lowStock: "",
      memberPrices: [],
      skuRebates: [],
      productId: "",
      skuCode: "",
      productSpecNames: tempArr,
      version: "",
      inputValue: "",
      inputVisble: false,
    };
  }

  /**
   * 上传sku
   */
  async uploadSkuImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 2 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 2MB!");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.formModel.skuStocks[this.productSkuIndex].pic = res.data;
  }
  deliverChangeHandle(e) {
    this.serviceAssuranceList[2].name = `${e}天发货`;
  }
  // 规格组合
  caleDescartes(list: NormType[]) {
    let assemble = [];
    assemble = list.map((item) => {
      return item.children;
    });
    if (assemble.length <= 1) {
      assemble = assemble[0];
    } else {
      assemble = assemble.reduce((total, currentValue) => {
        let res = [];
        total.forEach((t) => {
          currentValue.forEach((cv) => {
            if (t instanceof Array) {
              res.push([...t, cv]);
            } else {
              res.push([t, cv]);
            }
          });
        });
        return res;
      });
    }
    return assemble.map((item) => {
      return this.addSku(item);
    });
  }
  // 改变规格值
  async changeClassHandle(e) {
    // console.log("修改商品规格", e);
    const { type, list } = e;
    // 存储列表输入值
    if (this.goodNormDetailRef) {
      if (
        type === "addSpecValue" ||
        type === "delSpecValue" ||
        type === "sortSpecValue"
      ) {
        this.memoSpecList = await this.goodNormDetailRef.getNormList();
      } else {
        this.memoSpecList = [];
      }
    }
    this.formModel.productSpecs = list;
    this.formModel.skuStocks = this.caleDescartes(list);
  }
  // 改变规格列表
  changeNormList(e) {
    this.formModel.skuStocks = e;
  }
}
</script>
<style lang="scss">
@import "@/assets/styles/goods/goodMultiSpec.scss";
.input_number {
  .el-input__inner {
    text-align: left;
  }
}

//  .commission{
//   display: flex;
//   align-items: baseline;
//   margin-top: 25px;
//  margin-bottom: ;

// }
</style>
